package lagou.test;


import lagou.pojo.Products;
import lagou.resultmapper.ESSearchResultMapper;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class test1{

    @Autowired
    private ElasticsearchTemplate template;
    @Test
    public void fa(){
        System.out.println(1);
    }

    @Test
    public void testCreateIndex(){
        // 创建索引库，并指定实体类的字节码
        template.createIndex(Products.class);
    }

    @Test
    public void select(){
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        queryBuilder.withQuery(QueryBuilders.matchQuery("name", "哈哈"));
        queryBuilder.withPageable(PageRequest.of(0, 5, Sort.by(Sort.Direction.ASC, "price")));
        queryBuilder.withFilter(QueryBuilders.rangeQuery("price").gt(0).lt(5000));

        HighlightBuilder.Field title = new HighlightBuilder.Field("name");
        title.preTags("<hhh>");
        title.postTags("</hhh>");
        queryBuilder.withHighlightFields(title);
        AggregatedPage<Products> result = template.queryForPage(queryBuilder.build(), Products.class,new ESSearchResultMapper());

        long total = result.getTotalElements(); //包含的文档数量，即总共的条数
        int totalPages = result.getTotalPages(); //获取页码，总共的页数，这里并不是根据结果来找的（返回结果里并没有），他是根据计算来得出的，因为有总条数存在
        List<Products> list = result.getContent(); //获取本页数据的集合
        System.out.println("总条数 = " + total);
        System.out.println("总页数 = " + totalPages);
        System.out.println(list);

    }


}
